package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public SysUser findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //开始条件查询
        Page<SysUser> page = userDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public List<Role> findAll() {
        return userDao.findAll();
    }

    @Override
    public void add(Integer[] roles, SysUser sysUser) {
        userDao.add(sysUser);
        setCheckGroupAndCheckItem(sysUser.getId(),roles);
    }

    @Override
    public void edit(Integer[] roles, SysUser sysUser) {
//      * 1. 修改检查组基本信息
        userDao.update(sysUser);
//      * 2. 删除原来的检查组与检查项的关系
        userDao.deleteAssociation(sysUser.getId());
//      * 3. 添加检查组与检查型新的关系
        setCheckGroupAndCheckItem(sysUser.getId(), roles);
    }

    @Override
    public SysUser findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsBySykUserId(Integer id) {
        return userDao.findRoleIdsBySykUserId(id);
    }

    @Override
    public void delById(Integer id) {
        userDao.delByIds(id);
        userDao.delById(id);
    }

    private void setCheckGroupAndCheckItem(Integer sysUserID, Integer[] roles){
        if(sysUserID != null && roles != null && roles.length > 0){
            for (Integer rolesid : roles) {
                userDao.setCheckgroupAndCheckItem(sysUserID, rolesid);
            }
        }
    }
}
